package com.takeaway.ui.adapter

import android.support.v4.app.FragmentActivity
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.takeaway.R
import com.takeaway.model.beans.Order
import com.takeaway.utils.OrderObserable
import org.jetbrains.anko.find
import java.util.*
import kotlin.collections.ArrayList

// 订单的观察者
class OrderRvAdapter(val context: FragmentActivity?): RecyclerView.Adapter<RecyclerView.ViewHolder>(), Observer {

    init {
        // 观察者和被观察者建立绑定关系
        OrderObserable.instance.addObserver(this)
    }

    /// 观察者更新方法
    override fun update(observer: Observable?, data: Any?) {

        Log.e("OrderRvAdapter","观察者收到消息")
    }

    private var orderList: List<Order> = ArrayList()

    fun setData(data: List<Order>) {
        orderList = data
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerView.ViewHolder {
//        val itemView = View.inflate(context, R.layout.item_order_item, null)
        // 如果布局没有填充满
        val itemView = LayoutInflater.from(context).inflate(R.layout.item_order_item, p0, false)
        return OrderViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return orderList.size
    }

    override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int) {
        (p0 as OrderViewHolder).bindData(orderList[p1])
    }

    inner class OrderViewHolder(item: View): RecyclerView.ViewHolder(item) {

        fun bindData(order: Order) {
            tv_order_item_seller_name.text = order.name
            tv_order_item_type.text = order.type
        }


        private val tv_order_item_seller_name: TextView
        private val tv_order_item_type: TextView
        init {
            // 绑定视图
            tv_order_item_seller_name = item.find(R.id.tv_order_item_seller_name)
            tv_order_item_type = item.find(R.id.tv_order_item_type)
        }
    }
}